import { useState, useRef, useEffect } from 'react'
import { createPortal } from 'react-dom'
import { ChevronDown, Database } from 'lucide-react'

interface TopicSelectorProps {
  topics: string[]
  selectedTopic: string | null
  onTopicChange: (topic: string | null) => void
  disabled?: boolean
}

export default function TopicSelector({
  topics,
  selectedTopic,
  onTopicChange,
  disabled = false
}: TopicSelectorProps) {
  const [searchTerm, setSearchTerm] = useState('')
  const [showDropdown, setShowDropdown] = useState(false)
  const [dropdownPosition, setDropdownPosition] = useState({ top: 0, left: 0, width: 0 })
  const inputRef = useRef<HTMLInputElement>(null)

  // 过滤Topic列表
  const filteredTopics = topics.filter(topic =>
    topic.toLowerCase().includes(searchTerm.toLowerCase())
  )

  // 计算下拉框位置
  useEffect(() => {
    if (showDropdown && inputRef.current) {
      const rect = inputRef.current.getBoundingClientRect()
      setDropdownPosition({
        top: rect.bottom + window.scrollY,
        left: rect.left + window.scrollX,
        width: rect.width
      })
    }
  }, [showDropdown])
  return (
    <div className="relative">
      <label className="block text-sm font-semibold text-gray-700 mb-2">
        选择Topic
        <span className="ml-2 px-2 py-1 bg-primary-100 text-primary-700 text-xs rounded-full font-medium">
          {topics.length} 个可用
        </span>
      </label>
      <div className="relative">
        <input
          ref={inputRef}
          type="text"
          value={selectedTopic || ''}
          onChange={(e) => {
            const value = e.target.value
            onTopicChange(value || null)
            setSearchTerm(value)
            setShowDropdown(true)
          }}
          onFocus={() => setShowDropdown(true)}
          disabled={disabled}
          placeholder="搜索或选择Topic..."
          className="input w-full pr-10 bg-white border-2 border-gray-300 focus:border-primary-500 transition-colors"
        />
        <Database className="absolute right-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-primary-500 pointer-events-none" />
      </div>

      {topics.length === 0 && (
        <p className="text-xs text-gray-500 mt-1">
          没有可用的Topic
        </p>
      )}

      {/* 使用Portal渲染下拉列表到body，避免被父容器截断 */}
      {showDropdown && !disabled && filteredTopics.length > 0 && createPortal(
        <>
          {/* 点击外部关闭下拉框 */}
          <div
            className="fixed inset-0 z-40"
            onClick={() => setShowDropdown(false)}
          />

          {/* 下拉列表 */}
          <div
            className="absolute z-50 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-auto"
            style={{
              top: dropdownPosition.top,
              left: dropdownPosition.left,
              width: dropdownPosition.width,
              minWidth: '200px'
            }}
          >
            {filteredTopics.slice(0, 20).map(topic => (
              <div
                key={topic}
                onClick={() => {
                  onTopicChange(topic)
                  setShowDropdown(false)
                  setSearchTerm('')
                }}
                className="px-3 py-2 hover:bg-gray-50 cursor-pointer border-b border-gray-100 last:border-b-0 truncate"
              >
                <div className="font-medium text-sm truncate" title={topic}>{topic}</div>
              </div>
            ))}
            {filteredTopics.length > 20 && (
              <div className="px-3 py-2 text-xs text-gray-500 bg-gray-50">
                还有 {filteredTopics.length - 20} 个Topic，请继续输入以筛选
              </div>
            )}
          </div>
        </>,
        document.body
      )}
    </div>
  )
}
